
//SEARCH.JS
//used for searching listings and recordings
// Author: Wilco

function searchUtils() {}
searchUtils.prototype.constructor = searchUtils;
searchUtils.prototype =
{	noKeyPressesSinceUpdate: -1,
	noKeyPressesToUpdate: 3,
	minLength: 3,
	prevPrevSearch: null,
	prevSearch: null,
	template: null,
	timer: null,
	searchData: null,
	loadPage: function()
	{
		if (DEBUG) console.log('Loading search script');
	},
    loadHooks: function()
    { 
		if (DEBUG) console.log('Loading search hooks');
		$('#SearchInput').bind('keyup',this.onKeyPress.bindAsEventListener(this)); 

        LoadFile(SkinDir + 'search.html', this.onLoadTemplate.bind(this));
    },
    onLoadTemplate: function(response)
    {
		this.template = new Template();
		this.template.load(response);
	},
	onKeyPress: function(event)
	{
		var value = $('#SearchInput').val();
		this.noKeyPressesSinceUpdate++;
		
		//If nothing reload full page immediately
		if (value == '')
		{   //Remove timer
			if (this.timer!=null)
			{
				clearTimeout(this.timer);
				this.timer = null;
			}
			//Abort previous searches
			if (this.prevSearch)
				this.prevSearch.abort();
			if (this.prevPrevSearch)
				this.prevPrevSearch.abort();
			
			PageChange('main');
			return;
		}
		if (this.noKeyPressesSinceUpdate == 0)
		{	//First firing, check for length
			if (value.length >= this.minLength)
			{
				this.runSearch(value);
				return;
			} else
				this.noKeyPressesSinceUpdate = value.length;

		}
		else if (this.noKeyPressesSinceUpdate >= this.noKeyPressesToUpdate && value.length >= this.minLength)
		{	//Check we have made enough key presses and string is long enough
			this.runSearch(value);
			this.noKeyPressesSinceUpdate = 0
			return;
		}
		
		//Handle timer
		if (this.timer!=null)
		{
			clearTimeout(this.timer);
			this.timer = null;
		}
		this.timer = setTimeout(this.onTimeout.bind(this),1000);
	},
	onTimeout: function()
	{
		var value = $('#SearchInput').val();;
		this.runSearch(value);
	},
    runSearch: function(search_str)
    {
		//Run at max 2 concurrent searches, stopping the current search if active
		if (this.prevPrevSearch != null)
		{
			if (this.prevSearch != null)
			{	//Cancel last search
				this.prevSearch.abort();
			}
		}
		else
		{	//move last search to end
			if (this.prevSearch != null)
				this.prevPrevSearch = this.prevSearch;
		}
		this.prevSearch = this.search(search_str);
    },
	search: function(search_str)
	{
		var fileURL = ServiceDir + 'search?search=' + search_str;
		return LoadFile(fileURL,this.onSearchResult.bind(this));
	},
	onSearchResult: function(response)
	{
		this.searchData = eval("(" + response + ")");
		var searchData = this.searchData;
		var tmpl = this.template.clone();
		var listTmpl = tmpl.removeSubTemplate('list');
		var artistItemTmpl = listTmpl.removeSubTemplate('artist_item');
		var albumItemTmpl = listTmpl.removeSubTemplate('album_item');
		var songItemTmpl = listTmpl.removeSubTemplate('song_item');
		
		var newTmpl = null;
		var artistItems = [];
		for(var i=0;i<searchData.artists.length;i++)
		{
            newTmpl = artistItemTmpl.clone();
            newTmpl.addData({    artist: searchData.artists[i].name,
								 index: i,
								artist_uri: encodeURIComponent(searchData.artists[i].name),
                        });
			artistItems.push(newTmpl);
		}
		listTmpl.addSubTemplate('artist_item',artistItems);
		
		var albumItems = [];
		for(var i=0;i<searchData.albums.length;i++)
		{
            newTmpl = albumItemTmpl.clone();
            newTmpl.addData({    album: searchData.albums[i].name,
								 index: i,
								album_uri: encodeURIComponent(searchData.albums[i].name),
                        });
			albumItems.push(newTmpl);
		}
		listTmpl.addSubTemplate('album_item',albumItems);
		
		var songItems = [];
		for(var i=0;i<searchData.tracks.length;i++)
		{
            newTmpl = songItemTmpl.clone();
            newTmpl.addData({    title: searchData.tracks[i].name,
								song_uri: encodeURIComponent(searchData.tracks[i].name),
								index: 		searchData.tracks[i].index,
                        });
            songItems.push(newTmpl);
		}
		listTmpl.addSubTemplate('song_item',songItems);
		document.getElementById('pagelist').innerHTML = listTmpl.parse();
	},
}

if (gLoadedScriptObjects['search'] == undefined)
	gLoadedScriptObjects['search'] = new searchUtils();
	
gLoadedScriptObjects['search'].loadHooks();